import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../../core/theme/app_colors.dart';
import '../../core/theme/app_text_styles.dart';
import '../../core/constants/app_constants.dart';
import '../../core/constants/emotion_constants.dart';

/// 情绪选择器组件
/// Emotion selector widget for choosing emotions
class EmotionSelectorWidget extends StatefulWidget {
  /// 情绪选择回调
  /// Emotion selection callback
  final Function(String emotionType, int intensity)? onEmotionSelected;
  
  /// 是否显示强度滑块
  /// Whether to show intensity slider
  final bool showIntensitySlider;
  
  /// 初始选中的情绪类型
  /// Initially selected emotion type
  final String? initialEmotionType;
  
  /// 初始强度值
  /// Initial intensity value
  final int? initialIntensity;
  
  /// 是否启用选择
  /// Whether selection is enabled
  final bool enabled;
  
  /// 网格列数
  /// Grid column count
  final int crossAxisCount;

  const EmotionSelectorWidget({
    super.key,
    this.onEmotionSelected,
    this.showIntensitySlider = true,
    this.initialEmotionType,
    this.initialIntensity,
    this.enabled = true,
    this.crossAxisCount = 4,
  });

  @override
  State<EmotionSelectorWidget> createState() => _EmotionSelectorWidgetState();
}

class _EmotionSelectorWidgetState extends State<EmotionSelectorWidget>
    with TickerProviderStateMixin {
  late AnimationController _animationController;
  late AnimationController _pulseController;
  late Animation<double> _scaleAnimation;
  late Animation<double> _pulseAnimation;
  
  String? _selectedEmotionType;
  double _intensity = 5.0;
  
  @override
  void initState() {
    super.initState();
    _initAnimations();
    _initValues();
  }

  @override
  void dispose() {
    _animationController.dispose();
    _pulseController.dispose();
    super.dispose();
  }

  /// 初始化动画
  /// Initialize animations
  void _initAnimations() {
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 200),
      vsync: this,
    );
    
    _pulseController = AnimationController(
      duration: const Duration(milliseconds: 1000),
      vsync: this,
    );

    _scaleAnimation = Tween<double>(
      begin: 1.0,
      end: 0.95,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: Curves.easeInOut,
    ));
    
    _pulseAnimation = Tween<double>(
      begin: 1.0,
      end: 1.1,
    ).animate(CurvedAnimation(
      parent: _pulseController,
      curve: Curves.easeInOut,
    ));
  }

  /// 初始化值
  /// Initialize values
  void _initValues() {
    _selectedEmotionType = widget.initialEmotionType;
    _intensity = (widget.initialIntensity ?? 5).toDouble();
  }

  /// 处理情绪选择
  /// Handle emotion selection
  void _onEmotionTap(String emotionType) {
    if (!widget.enabled) return;
    
    setState(() {
      if (_selectedEmotionType == emotionType) {
        // 如果点击已选中的情绪，触发回调
        // If tapping already selected emotion, trigger callback
        _triggerCallback();
      } else {
        // 选择新情绪
        // Select new emotion
        _selectedEmotionType = emotionType;
        if (!widget.showIntensitySlider) {
          // 如果不显示强度滑块，直接触发回调
          // If intensity slider is not shown, trigger callback directly
          _triggerCallback();
        }
      }
    });
    
    // 播放选择动画
    // Play selection animation
    _animationController.forward().then((_) {
      _animationController.reverse();
    });
    
    // 播放脉冲动画
    // Play pulse animation
    _pulseController.forward().then((_) {
      _pulseController.reverse();
    });
  }

  /// 处理强度变化
  /// Handle intensity change
  void _onIntensityChanged(double value) {
    if (!widget.enabled) return;
    
    setState(() {
      _intensity = value;
    });
  }

  /// 触发回调
  /// Trigger callback
  void _triggerCallback() {
    if (_selectedEmotionType != null && widget.onEmotionSelected != null) {
      widget.onEmotionSelected!(_selectedEmotionType!, _intensity.round());
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 情绪网格
        // Emotion grid
        _buildEmotionGrid(),
        
        if (widget.showIntensitySlider && _selectedEmotionType != null) ...[
          SizedBox(height: 24.h),
          
          // 强度滑块
          // Intensity slider
          _buildIntensitySlider(),
          
          SizedBox(height: 16.h),
          
          // 确认按钮
          // Confirm button
          _buildConfirmButton(),
        ],
      ],
    );
  }

  /// 构建情绪网格
  /// Build emotion grid
  Widget _buildEmotionGrid() {
    final emotions = EmotionConstants.getAllEmotionTypes();
    
    return GridView.builder(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: widget.crossAxisCount,
        crossAxisSpacing: 16.w,
        mainAxisSpacing: 16.h,
        childAspectRatio: 1.0,
      ),
      itemCount: emotions.length,
      itemBuilder: (context, index) {
        final emotionType = emotions[index];
        final isSelected = _selectedEmotionType == emotionType;
        
        return _buildEmotionItem(emotionType, isSelected);
      },
    );
  }

  /// 构建情绪项
  /// Build emotion item
  Widget _buildEmotionItem(String emotionType, bool isSelected) {
    final color = EmotionConstants.getEmotionColor(emotionType);
    final icon = EmotionConstants.getEmotionIcon(emotionType);
    final label = EmotionConstants.getEmotionLabel(emotionType);
    final emoji = EmotionConstants.getEmotionEmoji(emotionType);
    
    return AnimatedBuilder(
      animation: _animationController,
      builder: (context, child) {
        final scale = isSelected ? _scaleAnimation.value : 1.0;
        
        return Transform.scale(
          scale: scale,
          child: AnimatedBuilder(
            animation: _pulseController,
            builder: (context, child) {
              final pulseScale = isSelected ? _pulseAnimation.value : 1.0;
              
              return Transform.scale(
                scale: pulseScale,
                child: GestureDetector(
                  onTap: () => _onEmotionTap(emotionType),
                  child: AnimatedContainer(
                    duration: const Duration(milliseconds: 200),
                    decoration: BoxDecoration(
                      color: isSelected 
                          ? color.withOpacity(0.2)
                          : Colors.transparent,
                      borderRadius: BorderRadius.circular(AppConstants.radiusMedium),
                      border: Border.all(
                        color: isSelected 
                            ? color
                            : color.withOpacity(0.3),
                        width: isSelected ? 2 : 1,
                      ),
                      boxShadow: isSelected 
                          ? [
                              BoxShadow(
                                color: color.withOpacity(0.3),
                                blurRadius: 8,
                                offset: const Offset(0, 2),
                              ),
                            ]
                          : null,
                    ),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        // 表情符号或图标
                        // Emoji or icon
                        if (emoji.isNotEmpty)
                          Text(
                            emoji,
                            style: const TextStyle(fontSize: 24),
                          )
                        else
                          Icon(
                            icon,
                            size: 24,
                            color: isSelected ? color : color.withOpacity(0.7),
                          ),
                        
                        const SizedBox(height: 4),
                        
                        // 标签
                        // Label
                        Text(
                          label,
                          style: AppTextStyles.bodySmall.copyWith(
                            color: isSelected 
                                ? color
                                : AppColors.textSecondary,
                            fontWeight: isSelected 
                                ? FontWeight.w600
                                : FontWeight.normal,
                          ),
                          textAlign: TextAlign.center,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ],
                    ),
                  ),
                ),
              );
            },
          ),
        );
      },
    );
  }

  /// 构建强度滑块
  /// Build intensity slider
  Widget _buildIntensitySlider() {
    final color = _selectedEmotionType != null 
        ? EmotionConstants.getEmotionColor(_selectedEmotionType!)
        : AppColors.primary;
    
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              '情绪强度',
              style: AppTextStyles.titleSmall.copyWith(
                fontWeight: FontWeight.w600,
              ),
            ),
            Container(
              padding: const EdgeInsets.symmetric(
                horizontal: 8,
                vertical: 4,
              ),
              decoration: BoxDecoration(
                color: color.withOpacity(0.1),
                borderRadius: BorderRadius.circular(AppConstants.radiusSmall),
                border: Border.all(
                  color: color.withOpacity(0.3),
                  width: 1,
                ),
              ),
              child: Text(
                '${_intensity.round()}',
                style: AppTextStyles.titleSmall.copyWith(
                  color: color,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ],
        ),
        
        const SizedBox(height: AppConstants.spacingSmall),
        
        SliderTheme(
          data: SliderTheme.of(context).copyWith(
            activeTrackColor: color,
            inactiveTrackColor: color.withOpacity(0.3),
            thumbColor: color,
            overlayColor: color.withOpacity(0.2),
            valueIndicatorColor: color,
            valueIndicatorTextStyle: AppTextStyles.bodySmall.copyWith(
              color: Colors.white,
              fontWeight: FontWeight.w600,
            ),
          ),
          child: Slider(
            value: _intensity,
            min: 1,
            max: 10,
            divisions: 9,
            label: EmotionConstants.getIntensityLabel(_intensity.round()),
            onChanged: widget.enabled ? _onIntensityChanged : null,
          ),
        ),
        
        // 强度标签
        // Intensity labels
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              '轻微',
              style: AppTextStyles.bodySmall.copyWith(
                color: AppColors.textTertiary,
              ),
            ),
            Text(
              '强烈',
              style: AppTextStyles.bodySmall.copyWith(
                color: AppColors.textTertiary,
              ),
            ),
          ],
        ),
      ],
    );
  }

  /// 构建确认按钮
  /// Build confirm button
  Widget _buildConfirmButton() {
    final color = _selectedEmotionType != null 
        ? EmotionConstants.getEmotionColor(_selectedEmotionType!)
        : AppColors.primary;
    
    return SizedBox(
      width: double.infinity,
      child: ElevatedButton(
        onPressed: widget.enabled ? _triggerCallback : null,
        style: ElevatedButton.styleFrom(
          backgroundColor: color,
          foregroundColor: Colors.white,
          elevation: 2,
          shadowColor: color.withOpacity(0.3),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(AppConstants.radiusMedium),
          ),
          padding: const EdgeInsets.symmetric(
            vertical: AppConstants.paddingMedium,
          ),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.check,
              size: 20,
            ),
            const SizedBox(width: AppConstants.spacingSmall),
            Text(
              '确认记录',
              style: AppTextStyles.titleSmall.copyWith(
                color: Colors.white,
                fontWeight: FontWeight.w600,
              ),
            ),
          ],
        ),
      ),
    );
  }
}